import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/commonApi.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class SettlementPage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isReadOnly;

  const SettlementPage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isReadOnly = false,
  });

  @override
  State<SettlementPage> createState() => _SettlementPageState();
}

class _SettlementPageState extends State<SettlementPage> {
  final _formKey = GlobalKey<FormState>();
  final _bankNameController = TextEditingController();
  final _bankAccountController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _bankNameController.text = widget.state.person["bankName"];
    _bankAccountController.text = widget.state.person["bankAccount"];
  }

  @override
  void dispose() {
    _bankNameController.dispose();
    _bankAccountController.dispose();
    super.dispose();
  }

  
  Future<void> _saveForm() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    EasyLoading.show(status: "保存中...");

    try {
      widget.state.updatePersonSettlementInfo(
        bankName: _bankNameController.text,
        bankAccount: _bankAccountController.text,
      );

      widget.onStateChanged();
      EasyLoading.dismiss();
      EasyLoading.showSuccess("保存成功");
      if (mounted) {
        Navigator.pop(context);
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError("保存失败：${e.toString()}");
    }
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '结算账户',
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            // 只读提示
            if (widget.isReadOnly) _buildReadOnlyTip(),
            TextFormField(
              controller: _bankNameController,
              enabled: !widget.isReadOnly,
              decoration: InputDecoration(
                labelText: '开户银行',
                hintText: '请输入开户银行',
                suffixIcon: Icon(Icons.account_balance_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入开户银行';
                }
                if (value.length < 2) {
                  return '银行名称长度不能小于2个字符';
                }
                if (value.length > 50) {
                  return '银行名称长度不能超过50个字符';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _bankAccountController,
              enabled: !widget.isReadOnly,
              decoration: InputDecoration(
                labelText: '银行账号',
                hintText: '请输入银行账号',
                suffixIcon: Icon(Icons.credit_card_outlined),
              ),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入银行账号';
                }
                if (!RegExp(r'^\d{16,19}$').hasMatch(value)) {
                  return '请输入正确的银行账号';
                }
                return null;
              },
            ),
            const SizedBox(height: 24),
            // 只有在非只读模式下才显示保存按钮
            if (!widget.isReadOnly)
              SizedBox(
                width: double.infinity,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeVars.colorPrimary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 